/**
 * 
 */
package com.surelution.lansao.crawler

import groovy.sql.Sql

import javax.servlet.http.Cookie

import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.NameValuePair
import org.apache.http.client.HttpClient
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
import org.json.JSONArray
import org.json.JSONObject

import com.surelution.lansao.Member;
import com.surelution.lansao.Partner;
import com.surelution.lansao.WxRawMessage;
import com.surelution.lansao.WxRawUser;

/**
 * @author <a href="mailto:guangzong.syu@gmail.com">Guangzong</a>
 *
 */
class ProcessHelper {
//	private static String username = "13764500179@qq.com"
//	private static String pwd = "b132978a100461b2252444ddc0c59bb6"
	
	public static void main(String[] args) {
//		updateUsers()
		HttpClient hc = buildClient("13764500179@qq.com","b132978a100461b2252444ddc0c59bb6")
		List<RawUserInfo> ruies = getUsers(hc)
//		saveUsers(ruies)
//		ruies.each {rui->
//			List<RawMessageInfo> infoes = getUserMessages(hc, rui.fakeId)
//			RawMessageInfo sub = infoes.find {
//				it.source && it.content && it.source == "biz" && it.content.contains("联系电话：18001863596")
//			}
//			if(sub) {
//				println "fakeId:${rui.fakeId}, nickName:${rui.nickName}"
//			}
//		}
	}
	
	public static void saveUsers(List<RawUserInfo> infoes) {
		Sql sql = Sql.newInstance( 'jdbc:mysql://localhost/lansao?useUnicode=true&characterEncoding=utf8', 'root',
			'', 'com.mysql.jdbc.Driver' )
		infoes.each {rui->
			def row = sql.firstRow("select count(id) from raw_user_info rui where rui.fake_id=?", rui.fakeId)
			if(row[0] == 0) {
				sql.execute("insert into raw_user_info(fake_id, nick_name) values(?,?)", [rui.fakeId, rui.nickName])
			}
		}
	}
	
	public static void updateUsers() {
		Sql sql = Sql.newInstance( 'jdbc:mysql://localhost/lansao?useUnicode=true&characterEncoding=utf8', 'root',
			'', 'com.mysql.jdbc.Driver' )
		sql.eachRow("select id, fake_id from raw_user_info where member_id is null") {row ->
			println "${row.id}, ${row.fake_id}"
		}
	}
	
	public static List<WxRawUser> getUsers(HttpClient httpclient) {
		List<WxRawUser> infoes = new ArrayList<WxRawUser>()
		String url = "http://mp.weixin.qq.com/cgi-bin/contactmanagepage?t=wxm-friend&lang=zh_CN&pagesize=100&pageidx=0&type=0&groupid=0";
		HttpGet get = new HttpGet(url)
		
		HttpResponse response = httpclient.execute(get);
		DataOutputStream dos = new DataOutputStream();
		
		InputStreamReader isr = new InputStreamReader(response.getEntity().content)
		BufferedReader br = new BufferedReader(isr)
		StringBuilder sb = new StringBuilder()
		boolean coll = false;
		br.each {
			if(coll && it.trim() == "</script>") {
				coll = false;
			}
			if(coll) {
				sb.append(it)
			}
			if(it.trim() == """<script id="json-friendList" type="json/text">""") {
				coll = true
			}
		}
		JSONArray s = new JSONArray(sb.toString())
		for(int i = 0; i < s.length(); i++) {
			JSONObject o = (JSONObject) s.get(i)
			String fakeId = o.getString("fakeId")
			String name = o.getString("nickName")
			WxRawUser info = new WxRawUser(fakeId:fakeId, nickName:name)
			infoes.add(info)
		}
		infoes
	}

	public static HttpClient buildClient(String username, String pwd) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
//		httpclient.a
		try {
			//TODO S
			HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN?");

			List <NameValuePair> nvps = new ArrayList <NameValuePair>();
			nvps.add(new BasicNameValuePair("username", username));
			nvps.add(new BasicNameValuePair("pwd", pwd));
			nvps.add(new BasicNameValuePair("imgcode", ""));
			nvps.add(new BasicNameValuePair("f", "json"));

			httpost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

			HttpResponse response = httpclient.execute(httpost);
			HttpEntity entity = response.getEntity();
			entity = response.getEntity();

			System.out.println("Login form get: " + response.getStatusLine());
			EntityUtils.consume(entity);

			System.out.println("Post logon cookies:");
			List<Cookie> cookies = httpclient.getCookieStore().getCookies();
			if (cookies.isEmpty()) {
				System.out.println("None");
			} else {
				for (int i = 0; i < cookies.size(); i++) {
					System.out.println("- " + cookies.get(i).toString());
				}
			}
		} catch(e) {

		}
		return httpclient
	}

	public static List<WxRawMessage> getUserMessages(HttpClient httpclient, String fakeId) {
		String url = "http://mp.weixin.qq.com/cgi-bin/singlemsgpage?fromfakeid=${fakeId}&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN"
		List<WxRawMessage> infoes = new ArrayList<WxRawMessage>()
		HttpGet get = new HttpGet(url)
		
		HttpResponse response = httpclient.execute(get);
		DataOutputStream dos = new DataOutputStream();
		
		InputStreamReader isr = new InputStreamReader(response.getEntity().content)
		BufferedReader br = new BufferedReader(isr)
		StringBuilder sb = new StringBuilder()
		boolean coll = false;
		br.each {
			if(coll && it.trim().indexOf("</script>") > 0) {
				coll = false;
			}
			if(coll) {
				sb.append(it)
			}
			if(it.trim().indexOf("""<script id="json-msgList" type="json">""") > 0 ){
				coll = true
			}
		}
		sb.append("]")
		JSONArray s = new JSONArray(sb.toString())
		for(int i = 0; i < s.length(); i++) {
			JSONObject o = (JSONObject) s.get(i)
			String fId = o.getString("fakeId")
			String source = o.getString("source")
			String dateTime = o.getString("dateTime")
			String content = o.getString("content")
			WxRawMessage info = new WxRawMessage(fakeId:fId, source:source, dateTime:dateTime, content:content)
			infoes.add(info)
		}
		infoes
	}

	public static void sendMessage(Partner partner, Member member, String content) throws Exception {
		def httpclient = buildClient(partner.wxUsername, partner.wxPassword)
		//TODO S
		HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&lang=zh_CN");

		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		nvps.add(new BasicNameValuePair("type", "1"));
		nvps.add(new BasicNameValuePair("content", content));
		nvps.add(new BasicNameValuePair("error", "false"));
		nvps.add(new BasicNameValuePair("tofakeid", member.fakeId));
		nvps.add(new BasicNameValuePair("ajax", "1"));

		httpost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

		HttpResponse response = httpclient.execute(httpost);
	}
}
